<template>
  <div>
    <el-dialog
      title="添加工单"
      :visible.sync="visible"
      width="700px"
      :close-on-click-modal="false"
    >
      <u-form
        ref="uFormRef"
        label-width='134px'
        v-model="form"
        :formArray="formArray"
        :detailArray="detailArray"
        :defaultForm="defaultForm"
        @submit="onsubmit"
        @close="visible = false"
        :mode="mode"
        v-loading="loading"
      >
        <template #deviceId="scope">
          <div class="form-item-wrap">
            <el-input
              placeholder="请输入设备ID或者点击选择设备按钮"
              v-model="form[scope.row.key]"
              style="flex: 1"
              clearable
              @change="checkDeviceIdValid"
            />
            <el-button
              v-show="!deviceData || !deviceData.deviceId"
              icon="el-icon-search"
              type="primary"
              style="margin-left: 10px;"
              @click="showSelectDeviceView">选择设备
            </el-button>
          </div>
        </template>

        <template #image="scope">
          <u-file-upload
            :value="form.image"
            :limit="3"
            :fileSize="10"
            @input="imageUploadChange"
          />
        </template>

        <template #operationUserName="scope">
          {{ form.orderStatus !== 0 ? form.operationUserName : '' }}
        </template>

        <template #orderStatus="scope">
          <el-tag size="small" effect="dark" :type="isTagType(form.orderStatus)">
            {{ getDictLabel(orderStatusOptions, form.orderStatus) }}
          </el-tag>
        </template>
      </u-form>
    </el-dialog>

    <select-device-dialog
      v-if="selectDeviceDialogVisible"
      v-model="selectDeviceDialogVisible"
      @select="handleSelectDevice"
    />
  </div>
</template>

<script>
import UForm from '@/components/uForm'
import {updateStatusLog} from "@/api/monitor/equipmentStatus";
import {addWorkOrder, updateWorkOrder} from "@/api/operationAndMonitoring/workOrder";
import {listManager} from "@/api/device/placeManager";
import SelectDeviceDialog from "@/views/operationAndMonitoring/workerOrder/components/SelectDeviceDialog";

export default {
  name: "AddWorkOrderDialog",
  components: {UForm, SelectDeviceDialog},
  props: {
    value: {
      type: Boolean,
      default: false
    },
    mode: {
      type: String,
      default: 'form'
    },
    deviceData: {
      type: Object
    },
    originForm: {
      type: Object,
      default() {
        return {}
      }
    },
    // 是否是异常日志使用到该组件,如果是需要回填异常信息、上报人相关内容
    isFaultLogUse: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 工单状态（0未处理、1处理完成、2不需要处理
      orderStatusOptions: [
        {label: '未处理', value: 0},
        {label: '处理完成', value: 1},
        {label: '不需要处理', value: 2},
      ],
      form: {},
      defaultForm: {
        deviceId: '',
        deploymentName: '',
        deploymentCode: '',
        operationUserCode: '',
        operationUserName: '',
        message: '',
        image: '',
        reportName: '',
        reportPhone: '',
      },
      formArray: [
        {
          label: "设备ID", key: "deviceId", col: 24, slot: "deviceId",
          rule: {required: true, message: '设备ID不能为空！', trigger: 'change'},
        },
        {label: "设备部署名称", key: "deploymentName", col: 24, type: "input", attr: {disabled: true}, placeholder: ' '},
        {
          label: "运维人员", key: "operationUserCode", col: 24, type: "select", options: [],
          rule: {required: true, message: '运维人员不能为空！', trigger: 'blur'},
        },
        {
          label: "异常内容", key: "message", col: 24, type: "textarea",
          rule: {required: true, message: '问题描述不能为空！', trigger: 'blur', attr: {resize: 'none'}},
        },
        {label: "照片", key: "image", col: 24, slot: "image"},
        {
          label: "报障人联系电话", key: "reportPhone", col: 24, type: "input",
        },
        {
          label: "报障人姓名", key: "reportName", col: 24, type: "input",
        },
      ],
      detailArray: [
        {label: "工单ID：", key: "id", col: 12, type: "text",},
        {label: "设备ID：", key: "deviceId", col: 12, type: "text",},
        {label: "设备部署名称：", key: "deploymentName", col: 12, type: "text", placeholder: ' '},
        {label: "运维人员：", key: "operationUserCode", col: 12, type: "select", options: []},
        {label: "异常内容：", key: "message", col: 24, type: "text", attr: {resize: 'none'}},
        {label: "照片：", key: "image", col: 24, type: "img"},
        {label: "报障人联系电话：", key: "reportPhone", col: 12, type: "text",},
        {label: "报障人姓名：", key: "reportName", col: 12, type: "text",},
        {label: "生成时间：", key: "createTime", col: 12, type: "time"},
        {label: "处理状态：", key: "orderStatus", col: 12, slot: 'orderStatus', type: "text"},
        {label: "原因及处理结果：", key: "dealResult", col: 12, type: "text"},
        {label: "处理人：", key: "operationUserName", col: 12, type: "slot", slot:'operationUserName' ,options: []},
        {label: "处理时间：", key: "dealTime", col: 12, type: "time"},
      ],
      loading: false,
      selectDeviceDialogVisible: false,
      // 是否为有效的设备id
      isValidDeviceId: true
    }
  },
  computed: {
    visible: {
      get() {
        return this.value
      },
      set(val) {
        if (!val) this.$refs.uFormRef.reset();
        return this.$emit('input', val)
      }
    },
    // 运维人员下拉框数据
    operationUserOptions() {
      return this.$store.state.device.operationUserOptions || []
    },
  },
  methods: {
    // tag样式
    isTagType(value) {
      switch (value) {
        case 0:
          return 'danger'
        case 1:
          return 'success'
        case 2:
          return 'info'
      }
    },
    // 选择设备列表弹窗 选择设备回调
    handleSelectDevice(deviceInfo) {
      this.isValidDeviceId = true;
      this.form.deviceId = deviceInfo.deviceId;
      this.form.deploymentCode = deviceInfo.deploymentCode;
      this.form.deploymentName = deviceInfo.deploymentName;
    },
    // 弹出选择设备弹窗
    showSelectDeviceView() {
      this.selectDeviceDialogVisible = true;
    },
    /** 查询该ID在设备部署管理列表是否存在*/
    checkDeviceIdValid(id) {
      this.loading = true;
      this.isValidDeviceId = false;
      // 请求参数
      const params = {
        deviceId: this.form.deviceId
      };
      listManager(params).then(response => {
          const list = response.rows;
          this.form.deploymentName = '';
        if (list.length) {
            this.isValidDeviceId = true;
            this.form.deploymentName = list[0].deploymentName
            this.form.deploymentCode = list[0].deploymentCode
          } else {
            this.$modal.confirmAlert('该设备ID不存在已部署设备列表，请重新输入！')
          }
        }
      ).finally(() => {
        this.loading = false;
      })
    },
    // 回填表单
    fillForm() {
      // 是否是异常日志使用到该组件,如果是需要回填异常信息、图片、上报人相关内容
      if (this.isFaultLogUse) {
        this.form.deviceId = this.deviceData.deviceId;
        this.form.deploymentName = this.deviceData.deploymentName;
        this.form.message = `${this.errorCode}${this.deviceData.errorMessage}`;
        this.form.image = this.deviceData.image;
        this.form.reportName = this.deviceData.reportName;
        this.form.reportPhone = this.deviceData.reportPhone;
      } else {
        this.form.deviceId = this.deviceData.deviceId;
        this.form.deploymentName = this.deviceData.deploymentName;
        this.form.deploymentCode = this.deviceData.deploymentCode;
      }

    },
    // 添加文件上传成功、删除图片时都会被调用
    imageUploadChange(imgUrl) {
      this.form.image = imgUrl
    },
    onsubmit(callBack) {
      if (!this.isValidDeviceId) {
        this.$modal.confirmAlert('该设备ID不存在已部署设备列表，请重新检查！');
        return callBack()
      }
      this.loading = true;
      const operation = this.operationUserOptions.find(item => item.value === this.form.operationUserCode)
      if (operation) this.form.operationUserName = operation.label;
      if (!this.form.id) {
        addWorkOrder(this.form).then((response) => {
          this.visible = false;
          this.$modal.msgSuccess("工单添加成功");
          this.$emit('getList')
        }).finally(() => {
          this.loading = false;
          callBack && callBack()
        });
      } else {
        updateWorkOrder(this.form).then((response) => {
          this.visible = false;
          this.$modal.msgSuccess("工单修改成功");
          this.$emit('getList')
        }).finally(() => {
          this.loading = false;
          callBack && callBack()
        });
      }

    }
  },
  watch: {
    operationUserOptions: {
      immediate: true,
      handler(newValue) {
        // 设置运维人员选项数据
        try {
          this.detailArray.forEach(item => {
            if (item.key === 'operationUserCode') item.options = newValue;
          })
          this.formArray.find(item => item.key === 'operationUserCode').options = newValue;
        } catch (e) {
          console.log("找不到对应表单项", e)
        }
      },
    },
    value: {
      immediate: true,
      handler(newValue) {
        if (newValue) {
          if (this.originForm && this.originForm.id) {
            // 修改
            this.form = JSON.parse(JSON.stringify(this.originForm));
          } else {
            // 新增
            this.form = JSON.parse(JSON.stringify(this.defaultForm));
            // 如果存在设备信息，自动回填表单设备ID和部署名称
            if (this.deviceData) this.fillForm();
          }
        }
      }
    }
  },
}
</script>

<style lang="scss" scoped>
.form-item-wrap {
  display: flex;
}
</style>
